import { defineStore } from 'pinia'
import { getGoodsList } from '@/api/goods2'
export const useShopcartStore = defineStore('shopcart', {
  state: () => ({
    goodsList: [],
    cartList: [],
  }),
  actions: {
    async initGoodsList() {
      const res = await getGoodsList(2)
      this.goodsList = res.data
    },
    addCart(goods) {
      // this.cartList.push(goods)
      //1.判断本次加入的商品，是否在购物车中，如果在，数量加1，不在，重置1
      const index = this.cartList.findIndex((item) => item.id == goods.id)
      if (index >= 0) {
        //existed
        this.cartList[index].num++
      } else {
        //no existed
        this.cartList.push({
          id: goods.id,
          name: goods.name,
          sell_point: goods.sell_point,
          price: goods.price,
          image: goods.image,
          num: 1,
        })
      }
    },
  },
})
